package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

/* table_name = live */
type Live struct {
	Id         int `orm:"auto;pk"`
	Url        string
	Company    *Company  `orm:"rel(one)" json:"-"`
	Status     bool      // 当前状态
	CreateTime time.Time `orm:"auto_now_add;type(datetime)"` // 注册时间
}

func GetLiveByCompanyId(id int) (*Live, error) {
	var l Live
	_, err := O.QueryTable("live").Filter("status", 1).Filter("company_id", id).All(&l)
	return &l, err
}

func GetLiveById(id int) (*Live, error) {
	var l = Live{
		Id: id,
	}
	err := O.Read(&l)
	return &l, err
}

func GetLiveListByKeyword(keyword string, page int, limit int) ([]*Live, error) {
	var c []*Live
	cond := orm.NewCondition().
		Or("Company__Name__icontains", keyword).
		Or("Company__location__icontains", keyword).
		Or("Company__information__icontains", keyword).
		Or("Company__address__icontains", keyword).
		Or("Company__website__icontains", keyword).
		Or("Company__official_account__icontains", keyword)
	_, err := O.QueryTable("live").
		Filter("status", 1).
		SetCond(cond).
		Limit(limit, page).All(&c)
	return c, err
}

func GetLiveListCompany(cList []*Live) ([]*Live, error) {
	var c *Live
	for _, c = range cList {
		if c.Company != nil {
			err := O.Read(c.Company)
			if err != nil {
				print(err.Error())
				return cList, err
			}
		}
	}
	return cList, nil
}

func UpdateCompanyLive(live Live) error {
	l, err := GetLiveByCompanyId(live.Company.Id)
	if err != nil || l == nil {
		live.Status = true
		_, err = O.Insert(&live)
	} else {
		live.Id = l.Id
		_, err = O.Update(&live,
			"url",
			"create_time")
	}

	return err
}
